<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Service\Facades\Pay;
use App\Service\Model\Orders;
use Carbon\Carbon;
use App\Service\Model\Cards;
use App\Service\Model\Agency;
use App\Service\Model\DayTotal;
use App\Service\Model\AgencySalary;
use App\Service\Model\OrderDetails;

/**
 * 快捷免密支付扣款
 * 
 */
class OrderExecute extends Command
{
    const PLATFORM_RATIO = 0.008;
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'order:execute';
    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '快捷免密支付扣款';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     * 
     * @return mixed
     */
    public function handle()
    {
        $orderDetails  = Orders::getOrdersExecute();
        
        //dd($orderDetails->toArray());
        
        if($orderDetails->count() > 0){
            foreach($orderDetails as $detail){
                $cusid   = $detail->cusid;
                $agreeid = $detail->agreeid;
                $amount  = $detail->amount;
                $orderId = $detail->order_no;
                $cardno  = $detail->getOriginal('cardno');
            
                if($detail->type == OrderDetails::type_pay){
                    //付款
                    $ret     = Pay::quickpass($orderId , $agreeid ,$amount , $cusid );
                }else{
                    //提现
                    $ret     = Pay::acctpay($cusid , $amount , $orderId ,$agreeid , 0 , 1);
                }
                if(Pay::check($ret)){
                    $detail->status   = OrderDetails::status_success;
                    $detail->response = objectToString($ret);
                    $detail->save();
                    //修改卡的计划状态
                    $this->changeStatus($cardno);
                    //计算分润
                    $this->salary($detail);
                }else{
                    $detail->status   = OrderDetails::status_failed;
                    $detail->response = objectToString($ret);
                    $detail->errmsg   = $ret->retmsg;
                    $detail->save();
                }
                // logger("{$orderId} order_no is executed , response : " , objectToArray($ret));
            }
        }else{
            Logger('The Order-Execute crontab is on the running '.Carbon::now());
        }
    }

    public function salary($order){
        if($order->type == OrderDetails::type_pay){
            //$fee    = $order->fee;
            $amount     = $order->amount;
            $agency_id  = $order->agency_id;
            $agency = Agency::find($agency_id);

            if($agency){
                
                //增加交易总金额
                DayTotal::incr($agency_id , 'total_amount', $amount);
                if($agency->level == 1){
                    //一级代理处理逻辑
                    $gain = $amount * (self::PLATFORM_RATIO - $agency->ratio);
                    
                    //增加一级代理总分润
                    DayTotal::incr($agency_id , 'total_gain', $gain);
                    //增加一级代理自己发展的下线分润
                    DayTotal::incr($agency_id ,  'my_gain'  , $gain);

                    AgencySalary::create([
                        'order_id'     => $order->getKey(),
                        'amount'       => $gain,
                        'agency_id'    => $agency_id,
                        'agency_name'  => $agency->name,
                        'agency_level' => $agency->level,
                    ]);
                    
                }else{
                      
                      //二级代理自己增加
                      $gain = round($amount * (self::PLATFORM_RATIO - $agency->ratio),2);
                      
                      DayTotal::incr($order->agency_id , 'total_gain', $gain);
                      DayTotal::incr($order->agency_id , 'my_gain'   , $gain);
                      AgencySalary::create([
                          'order_id'     => $order->getKey(),
                          'amount'       => $gain,
                          'agency_id'    => $agency_id,
                          'agency_name'  => $agency->name,
                          'agency_level' => $agency->level,
                      ]);
                      //父级增加
                      $parent_id    = $agency->parent_id;
                        
                      $parentAgency = Agency::find($parent_id);
                     
                      $sub_gain = round($amount * ( $agency->ratio - $parentAgency->ratio ),2);//二级减一级的费率
                      
                      DayTotal::incr($parent_id , 'sub_gain', $sub_gain);
                      DayTotal::incr($parent_id , 'total_gain', $sub_gain);
                      
                      AgencySalary::create([
                          'order_id'       => $order->getKey(),
                          'amount'         => $sub_gain,
                          'agency_id'      => $parent_id,
                          'agency_name'    => $parentAgency->name,
                          'agency_level'   => $parentAgency->level,
                          'sub_agency_id'  => $agency_id,
                    ]);
                }

            }
            

        }
      
        
    }


    private function changeStatus($cardno){
        $orderDetails  = OrderDetails::where('cardno',$cardno)->whereIn('status',[
            OrderDetails::status_default,OrderDetails::status_failed,
        ])->get();
        
        if($orderDetails->count()  == 0){
            Cards::where('cardno',$cardno)->update(['plan_status'=>Cards::plan_status_off]);
            Orders::whereKey($orderDetails->order_id)->update(['status'=>Orders::status_success]);
        }

    }
}
